// Copyright (c) Microsoft Corporation. All rights reserved.

using System;
using System.Collections.Generic;
using System.Diagnostics;

using Microsoft.TeamFoundation.Migration.Toolkit.Wit;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Microsoft.TeamFoundation.Migration.Toolkit.Linking
{
    /// <summary>
    /// Generic external link.
    /// </summary>
    public class WorkItemExternalLink : WorkItemExternalLinkBase
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="linkType">TFS link type</param>
        /// <param name="sourceUri">URI of the source work item</param>
        /// <param name="targetUri">URI of the target work item</param>
        /// <param name="comment">Comment</param>
        public WorkItemExternalLink(
            string linkType,
            string sourceUri,
            string targetUri,
            string comment)
            : base(linkType, sourceUri, targetUri, comment)
        {
            // Link must point to an external artifact.
            if (!TfsExternalArtifactHandler.IsMyUri(targetUri))
            {
                throw new ToolkitArgException("targetUri");
            }
        }

        /// <summary>
        /// Creates a copy of the given link pointing to the given artifact.
        /// </summary>
        /// <param name="targetUri">New target</param>
        /// <returns>Copy of the link pointing to the new artifact</returns>
        public override ILink Redirect(
            string targetUri)
        {
            if (string.IsNullOrEmpty(targetUri))
            {
                throw new ArgumentNullException("targetUri");
            }
            return new WorkItemExternalLink(ExternalLinkType, SourceUri, targetUri, Comment);
        }

        /// <summary>
        /// Extracts location from the URI.
        /// </summary>
        /// <param name="uri">URI</param>
        /// <returns>Location</returns>
        protected override string LocationFromUri(
            string uri)
        {
            Debug.Assert(TfsExternalArtifactHandler.IsMyUri(uri), "Unsupported URI!");
            return uri.Substring(LinkingConstants.ExternalArtifactPrefix.Length);
        }

        /// <summary>
        /// Checks whether given link points to a generic external artifact.
        /// </summary>
        /// <param name="link">Link</param>
        /// <returns>True if the link points to a generic external artifact</returns>
        internal static bool IsMyLink(
            ExternalLink link)
        {
            return (!WorkItemChangeListLink.IsMyLink(link) &&
                !WorkItemLatestFileLink.IsMyLink(link) &&
                !WorkItemRevisionFileLink.IsMyLink(link));
        }
    }
}
